<?php
    class product_detail_Controller extends controllerBase
    {
        public function process()
        {
            core::checkSession();
            $oDatabase = new database();
            $this->aParams['titileproduct'] = "GẤU TRÚC PANDA";
            $this->aParams['location'] = 'No Location';
            $uri = URL::getLink('product/id/'.$this->iId);
            $this->aParams['uri'] = $uri;

            $this->aParams['uri_product'] = $uri;
            $this->aParams['idproduct'] = $this->iId;
            $graph = new Graphite();
            $graph->ns('bus',URL::getLink('id/bussiness'));
            $graph->setDebug( true );
            $graph->load($uri);  
            $ownUserUri = $graph->resource($uri)->getString('bus:#ownUser');
            if(isset($_SESSION['user_uri']))
            {
                if($ownUserUri == $_SESSION['user_uri'])
                {
                    $this->aParams['isOwnUser'] = true;
                }
            }
            $this->aParams['name'] = $graph->resource($uri)->get('bus:#name');
            $this->aParams['dongia'] = $graph->resource($uri)->getString('bus:#price');
            $this->aParams['motalong'] = $graph->resource($uri)->get('bus:#description');
            $this->aParams['images'] = $graph->resource($uri)->getList('bus:#image');
            $totalLike = 0;
            if($graph->resource($uri)->has('bus:#userLike'))
            {
                $UserLikes = $graph->resource($uri)->getList('bus:#userLike');
                $totalLike = count($UserLikes);
                if(isset($_SESSION['user_uri']))
                {
                    $isLiked = array_search($_SESSION['user_uri'],$UserLikes);
                    if($isLiked !== false)
                    {
                        $this->aParams['isLiked'] = true;
                    }
                }
            }
            $this->aParams['totalLike'] = $totalLike;
            $this->aParams['manufacturer'] = $graph->resource($uri)->get('bus:#hasManufacturer');
            $this->aParams['catelogy'] = $graph->resource($uri)->getString('bus:#hasCategory');
            if($graph->resource($uri)->get('bus:#location') !=null)
            {
                $this->aParams['location'] = $graph->resource($uri)->get('bus:#location');
            }

            $urimanufacturer = $graph->resource($uri)->get('bus:#hasManufacturer');
            $graph->load($urimanufacturer );
            $this->aParams['nameManufacturer'] = $graph->resource($urimanufacturer)->get('bus:#name');
            // Get category
            $uricatelogy = $graph->resource($uri)->get('bus:#hasCategory');
            $graph->load($uricatelogy );
            $this->aParams['nameCategory'] = $graph->resource($uricatelogy)->get('bus:#name');
            // Get user
            $this->aParams['nameUser'] = 'Not User';
            $str = $graph->resource($uri)->get('bus:#ownUser');
            if( $str!='')
            {
                $this->aParams['nameUser_login'] ='';
                $this->aParams['homepage_login'] = '';
                $this->aParams['is_Exit'] = '';
                $this->aParams['flowProduct'] = '';
                $this->aParams['flowUser'] = '';
                $this->aParams['image']='';
                $this->aParams['givenName']='';
                $this->aParams['locationPerson']='';
                $this->aParams['email']='';
                $this->aParams['hasSetting']='';
                $this->aParams['image']='';
                $uriuser = $graph->resource($uri)->get('bus:#ownUser');
                $this->aParams['uri_userupload'] = $uriuser;
                $graph->load($uriuser );
                $this->aParams['nameUser'] = $graph->resource($uriuser)->get('foaf:familyName');
                $this->aParams['givenName'] = $graph->resource($uriuser)->get('foaf:givenName');
                $this->aParams['locationPerson'] = $graph->resource($uriuser)->get('bus:location');
                $this->aParams['email'] = $graph->resource($uriuser)->get('foaf:mbox');
                $this->aParams['hasSetting'] = $graph->resource($uriuser)->get('bus:hasSetting');
                $this->aParams['image'] = $graph->resource($uriuser)->get('bus:image');

                if(isset($_SESSION['user_uri']))
                {
                    $uriuser_login = $_SESSION['user_uri'];
                    $flowproduct ='';
                    $flowuser ='';

                    $graph->load($uriuser_login);
                    $this->aParams['nameUser_login'] = $graph->resource($uriuser_login)->getLiteral('foaf:familyName');
                    $this->aParams['homepage_login'] = $graph->resource($uriuser_login)->getLiteral('foaf:givenName');
                    // Get list Follow product of current user login
                    if($graph->resource($uriuser_login)->has('bus:#followProduct'))
                    {
                        $aFollowProducts = $graph->resource($uriuser_login)->getList('bus:#followProduct');
                        if(count($aFollowProducts))
                        {
                            foreach($aFollowProducts as $sFollowProductUri)
                            {
                                if($sFollowProductUri == $uri)
                                { 
                                    $this->aParams['is_Exit']=true;
                                }
                                $temp = explode('/id/',$sFollowProductUri);
                                if($sFollowProductUri !='' && !strrpos($flowproduct,end($temp)))
                                {
                                    $flowproduct = $flowproduct.$sFollowProductUri.';';
                                }
                            }
                            $this->aParams['flowProduct'] = $flowproduct;
                        }
                    }

                    // Get list of Follow User of current user login
                    if($graph->resource($uriuser_login)->has('bus:#followUser'))
                    {
                        $aFollowUsers = $graph->resource($uriuser_login)->getList('bus:#followUser');
                        if(count($aFollowUsers))
                        {
                            foreach($aFollowUsers as $sFollowUserUri)
                            {
                                if($sFollowUserUri == $uriuser)
                                { 
                                    $this->aParams['is_Exit_user']=true;
                                }
                                $temp = explode('/id/',$sFollowUserUri);
                                if($sFollowUserUri !='' && !strrpos($flowuser,end($temp)))
                                {
                                    $flowuser = $flowuser.$sFollowUserUri.';';
                                }
                            }
                            $this->aParams['flowUser'] = $flowuser;
                        }
                    }
                }
                // Area UserName
                $this->aParams['nameUser_uri'] = $uriuser;
                $this->aParams['user_product'] = $str;
                if(isset($_SESSION['username']))
                {
                    if($_SESSION['user_uri'] == $str)
                    {
                        $this->aParams['is_editproduct'] = 'true';
                    }
                }
            }

            // Count comment and view 
            $this->aParams['viewComment'] = 0;
            $sQuery = 'SELECT * FROM binhluan WHERE masp_id ="'.$this->iId.'"';
            $aListproductComment =  $oDatabase->getListObject($sQuery);
            $this->aParams['viewComment'] = count($aListproductComment);
            $this->aParams['viewTotal'] = 0;

            // Update total View
            if( !isset($_COOKIE[$this->iId]))
            {
                $this->updateProductTotalView();
                setcookie($this->iId, 'data', time()+(int)$this->getTimeView(),'/');
            }
            if(isset($_SESSION['username']))
            {
                $_SESSION['Visitor'] = $_SESSION['username'];
            }
            // Get total View
            $otherUri = URL::getLink('id/'.$this->iId.'_other');
            $graph = new Graphite();
            $graph->ns('bus',URL::getLink('id/bussiness#'));    
            $graph->load($otherUri);  
            $this->aParams['viewTotal'] = $graph->resource($otherUri)->get('bus:totalView');

            $queryReletiveProduct = '
            PREFIX foaf: <http://xmlns.com/foaf/0.1/>
            PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>
            PREFIX dc: <http://purl.org/dc/elements/1.1/>
            PREFIX bus: <'.URL::getLink('id/bussiness#').'>

            SELECT * 
            WHERE
            {
            ?uri rdf:type bus:product.
            ?uri bus:name ?name.
            OPTIONAL {?uri bus:ownUser ?user.
            ?user foaf:familyName ?ownUser.}.
            ?uri bus:image ?image.
            ?uri bus:price ?price.
            ?uri bus:description ?description.
            ?uri bus:hasCategory ?catalog.
            FILTER(?catalog = "'.$this->aParams['catelogy'].'" && ?uri !="'.$uri.'")
            }LIMIT 10';
            $aProductRelative = $oDatabase->loadQuery($queryReletiveProduct);
            $arelatives = array();
            $this->aParams['notfound']='';
            if(count($aProductRelative['result']['rows'])!=0)
            {   
                $arelatives=$aProductRelative['result']['rows'];
            }

            $listRelative = array();
            if(count($arelatives)>0)
            {
                $len = 0;
                if(count($arelatives)>=4)
                    $len =4;
                else
                    $len = count($arelatives);
                for ($i = 0; $i < $len; $i++) {
                    $ran = rand(0,count($arelatives)-1);
                    array_push($listRelative,$arelatives[$ran]);
                    unset($arelatives[(int)$ran]);
                    sort($arelatives);

                }
            }
            $this->aParams['listRelativeproduct'] = $listRelative;


        }
        public function updateTotalView($view)
        {  
            $oDatabase = new database();
            $aCondition = array(
                'masp_id = "'.$this->iId => '"',

            );

            $aData = array(
                'totalview' => $view   
            );

            $result = $oDatabase->update('sanpham',$aData, $aCondition);
            $this->updateProductTotalView();
        }

        public function updateProductTotalView()
        {
            $oDatabase = new database();
            $graph = new Graphite();
            $graph->ns('bus',URL::getLink('id/bussiness#'));
            $uri = URL::getLink('product/id/'.$this->iId);
            $graph->load($uri );
            if($graph->resource($uri)->has('bus:otherProperties'))
            {
                $sTotalViewUri = $graph->resource($uri)->getString('bus:otherProperties');
                $graph = new Graphite();
                $graph->ns('bus',URL::getLink('id/bussiness#'));
                $graph->load($sTotalViewUri );
                $iTotalView = (int) $graph->resource($sTotalViewUri)->getString('bus:totalView');
                $iTotalView ++;
                $oDatabase->setProperity($sTotalViewUri,'bus:totalView',$iTotalView);
            }
            else
            {
                // Tao other properties for product
                $otherUri = URL::getLink('id/'.$this->iId.'_other');
                $ns = array(
                    'rdf' => 'http://www.w3.org/1999/02/22-rdf-syntax-ns#',
                    'foaf' => 'http://xmlns.com/foaf/0.1/',
                    'bus' => URL::getLink('id/bussiness#'),
                );
                $index = array(
                    $otherUri => array(
                        "bus:totalView" => array(
                            array( "value" => '0', 
                                "type" => "literal")
                        )
                    ) 
                );   
                $oDatabase->createResources($ns, $index,$this->iId.'_other'); 
                $oDatabase->setProperity($uri,'bus:otherProperties',$otherUri);
            }
        }

        public function getTotalView()
        {
            $oDatabase = new database();
            $product =  $oDatabase->getObject('SELECT * FROM sanpham WHERE masp_id ="'.$this->iId.'"');
            return $product-> totalview;
        }
        public function getTimeView()
        {
            $oDatabase = new database();
            $product =  $oDatabase->getObject('SELECT * FROM settingid WHERE tablename ="timeview"');
            return $product-> lastest_id;
        }
    }
?>